<template>
    <div class="container-page bg_linear">
        <el-tabs v-model="activeName" @tab-click="handleTabsClick">
            <el-tab-pane label="全部产品" name="-1"></el-tab-pane>
            <el-tab-pane label="有货产品" name="1"></el-tab-pane>
            <el-tab-pane label="无货产品" name="2"></el-tab-pane>
            <el-tab-pane label="上架产品" name="3"></el-tab-pane>
            <el-tab-pane label="下架产品" name="4"></el-tab-pane>
        </el-tabs>
        <div class="container-card" ref="containerRef">
            <div ref="pointsBoxRef" class="mb10">
                <searchBar :searchData="searchData" @search="onSearch" @refresh="onRefresh" />
            </div>
            <ElTable class="El-table" ref="tableRef" :loading="isLoading" row-key="id" :tableData="tableData"
                :columns="columns" :selection="selection" :single="single" :height="dynamicHeight"
                @loadScroll="loadScroll" @selection-change="onSelectionChange" @current-change="onCurrentChange"
                @sort-change="onSortChange" @filter-change="onFilterChange">
                <template #title="{ row }">
                    <div class="flex_row row-title">
                        <el-image class="avatar" :src="row.imgs" lazy :preview-src-list="[]"></el-image>
                        <div class="font_bule ml10 ellipsis" style="flex: 1;">
                            <p class="bold under-line ellipsis" @click.stop="onView(row)"> {{ row.title || "未知" }} </p>
                            <p class="ellipsis font_black9 font_size12">货号: {{ row.item_no || "--" }}</p>
                            <p class="ellipsis">
                                <el-tag
                                    v-for="(tag, intag) in (Array.isArray(row.tagsInfo) ? row.tagsInfo.slice(0, 4) : [])"
                                    :key="intag" :type="getTagType(intag)" size="mini" class="mr5">
                                    <span class="font_size10"> {{ tag }}</span>
                                </el-tag>
                            </p>
                        </div>
                        <div class="zhiding-box flex_row" v-if="row.istop == 1">
                            <img src="static/icon/zhiding.svg" class="zhi-icon">
                            <span class="font_size10 ml5">置顶</span>
                        </div>
                    </div>
                </template>
                <template #onsale="{ row }">
                    <div class="flex_row">
                        <div class="ellipsis" v-if="row.onsale == 1 || row.onsale_yd == 1">
                            <span class="font_green">已上架</span>
                            <el-popover placement="top" width="200" trigger="hover"
                                v-if="row.onsale_yds_name && row.onsale_yds_name.length > 0">
                                <span class="mr5" v-for="(yd, ydi) in row.onsale_yds_name" :key="ydi"> {{ yd.name
                                    }},</span>
                                <span class="under-line font_bule ml10" slot="reference"> 云店 </span>
                            </el-popover>
                        </div>
                        <div class="ellipsis font_red" v-else>已下架</div>
                    </div>
                </template>
            </ElTable>
        </div>
        <ayjDialog ref="ayjDialogRef" :fullscreen="false" width="70%" top="3vh" :title="goodsRow.title + '详情'"
            :slotFooter="false">
            <template v-if="goodsRow.id">
                <div style="height: 86vh;">
                    <goodsThree ref="goodsThreeRef" :xsgf="15" :isDrawerOpen="true"></goodsThree>
                </div>
            </template>
            <template v-else>
                <empty></empty>
            </template>
        </ayjDialog>
    </div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, watch, onUnmounted, computed, onBeforeUnmount, defineProps, defineEmits, nextTick } from '@vue/composition-api'
import ElTable from '@/components/commV2/Table/index.vue'
import customCtrl from "@/js/custom/CustomCtrl.js";
import { useDynamicHeight } from '@/hooks/useDynamicHeight'
import searchBar from './components/searchBar.vue'
import config from "@/js/conf/Config.js";
import lang from "@/js/conf/Lang.js";
import { buildTree, getTagType, toLocaleDateStr } from '@/utils/common.js'
import https from "@/js/https/Https.js";
import goodsThree from "@/components/goods/GoodsThree.vue";
const { proxy } = getCurrentInstance()

// 使用动态高度 hooks
const containerRef = ref(null)
const pointsBoxRef = ref(null)
const { dynamicHeight, updateHeight } = useDynamicHeight({
    containerRef: containerRef,
    subtractRef: pointsBoxRef,
    extraHeight: 70
})

const pageSizeNum = 20
const props = defineProps({
    // 表格是否开启多选
    selection: {
        type: Boolean,
        default: true
    },
    // 表格是否单选，默认多选
    single: {
        type: Boolean,
        default: false
    },
    // 扩展操作 内容
    extraColumns: {
        type: Array,
        default: () => []
    },
    // 是否是引用  客户页面组件 ，有一些是客户页面组件自身需要定制的操作，外界组件不参与客户页面组件默认操作，不能写死
    isCite: {
        type: Boolean,
        default: false
    },
    // 引用组件是否显示标签，标签需要额外处理
    isShowTag: {
        type: Boolean,
        default: false
    },
})

const activeName = ref('-1')
// 客户列表相关状态
const isLoading = ref(false)
const tableData = ref([])
const tableRef = ref(null) // 添加表格引用
const goodQuery = ref({
    is_sale: "", //是否用于开单 1 是 2否 1 的时候返回所有app上架产品
    catid: "", //分类
    brand: "", //品牌
    code: "", //条码值
    is_stock: "", //是否有货 1 是2否
    qty: "", //是否有货 1 是2否
    onsale: "", //是否在app上架 预留
    idyun: "", //云店id
    onsale_yd: "", //是否云店上架 1是2否
    attention: "", //筛选菜蔬 1 ：30天内未销售的产品 2： 7天内发布的产品 3：30天内发布的产品
    kw: "", //搜索关键词
    storeid: "", //仓库I
    suppid: "", //来源
    uid_cp: '', // 经办人
})
const custPage = ref(0)
const pageSize = ref(pageSizeNum)
const hasMore = ref(false)
const md = ref(null)

// 搜素数据集合
const searchData = ref({
    tag_ls: [], // 标签
    onsale_yds: [], // 小程序
    yd_ls: [], // 云店
    ucp_ls: [], // 经办人
    store_ls: [], // 仓库
    cat_list: [], // 类别
    attion_ls: [], // 关注
    supp_ls: [], // 来源
})

onMounted(() => {
    // 获取产品列表
    getGoodsList()
    // 获取经手人列表
    createdUcpList()
    // 动态修改筛选器按钮样式
    applyFilterButtonStyles()
    // 获取供货商列表
    // getcgSuppList()
})

const handleTabsClick = (e) => {
    goodQuery.value.is_stock = e.name == '-1' ? '' : e.name;
    onSelectRefresh({});
}

const ayjDialogRef = ref(null)
const goodsRow = ref({})
const goodsThreeRef = ref(null)
const onView = (row) => {
    goodsRow.value = row
    ayjDialogRef.value.open()
    nextTick(() => {
        goodsThreeRef.value.loadGoodsInfo(row.id);
    })
}

const onSearch = (query) => {
    onSelectRefresh(query)
}

const onRefresh = (query) => {
    onSelectRefresh(query)
}

const onSelectRefresh = (query) => {
    custPage.value = 0
    tableData.value = []
    goodQuery.value = {
        ...goodQuery.value,
        ...query
    }
    getGoodsList()
}

/*** 获取产品列表  GOODS_LIST ***/
const getGoodsList = async () => {
    if (isLoading.value) return;
    isLoading.value = true;
    let url = md.value == 12 ? config.CK_STORE_GOODS_LS : config.GOODS_LIST;
    let param = {};

    param = goodQuery.value;
    param.pfrom = custPage.value * pageSize.value;
    param.pnum = pageSize.value;
    let res = await proxy.$api({ url: url, data: param });
    let result = res?.data
    isLoading.value = false;
    if (!res || !result) {
        return;
    }
    // 分类
    if (result.catlist && result.catlist.length > 0) {
        const treeData = buildTree(result.catlist);
        searchData.value.cat_list = treeData;
    }
    // 仓库
    if (result.store_ls && custPage.value == 0) {
        searchData.value.store_ls = filterDataFormat(result.store_ls);
    }
    // 云店
    if (result.yd_ls && custPage.value == 0) {
        searchData.value.yd_ls = filterDataFormat(result.yd_ls);
    }
    // 类别
    if (result.attion_ls && custPage.value == 0) {
        searchData.value.attion_ls = filterDataFormat(result.attion_ls);
    }
    // 标签
    if (result.tag_ls && custPage.value == 0) {
        searchData.value.tag_ls = filterDataFormat(result.tag_ls);
    }
    // 上架分类
    if (result.onsale_yds && custPage.value == 0) {
        searchData.value.onsale_yds = result.onsale_yds.map(item => {
            return {
                label: item.name_rel,
                value: item.idyun,
            }
        })
    }
    if (result.qty_count) {
        qty_count.value = result.qty_count;
    }
    // 商品列表
    if (result.goodsInfo && result.goodsInfo.length > 0) {
        result.goodsInfo = result.goodsInfo.map(item => {
            const onsale_yds_name = [];
            // 遍历 item.onsale_yds 数组
            if (item.onsale_yds && Array.isArray(item.onsale_yds)) {
                item.onsale_yds.forEach(vm => {
                    // 在 aaa 数组中查找匹配的对象
                    const matchedObj = result?.yd_ls.find(obj => obj.idyun === vm);
                    if (matchedObj) {
                        onsale_yds_name.push(matchedObj);
                    }
                });
            }
            return {
                ...item,
                atime: toLocaleDateStr(item.atime),
                onsale_yds_name: onsale_yds_name
            }
        })
        tableData.value = tableData.value.concat(result.goodsInfo);
        hasMore.value = result.goodsInfo.length >= pageSizeNum;
    } else {
        hasMore.value = false
    }
}

// 获取供货商列表
const getcgSuppList = async () => {
    let data = {
        pfrom: 0,
        pnum: 100,
    };
    const res = await https.cgSuppList(data);
    if (res.data && res.data.supp_ls) { }
}

// 过滤筛选标签
function filterDataFormat(arr) {
    if (!arr || !Array.isArray(arr)) return [];
    return arr.map(obj => {
        // 处理 attion_ls 的特殊格式
        if (obj.hasOwnProperty('key') && obj.hasOwnProperty('name') && obj.hasOwnProperty('val')) {
            return {
                value: obj.val,
                label: obj.name
            };
        }
        // 处理其他格式
        const result = {};
        if (obj.hasOwnProperty('idyun')) result.value = obj.idyun;
        if (obj.hasOwnProperty('id')) result.value = obj.id;
        if (obj.hasOwnProperty('name')) result.label = obj.name;
        if (obj.hasOwnProperty('title')) result.label = obj.title;
        if (obj.hasOwnProperty('val')) result.value = obj.val;
        return result;
    });
}

// 经办人数据
const createdUcpList = async () => {
    let param = {
        md: "xs",
        ch: 2
    }
    let res = await proxy.$api({ url: config.UCP_LS, data: param });
    if (res && res.status == 1) {
        if (!res.data) return;
        searchData.value.ucp_ls = res.data.map(item => ({
            value: item.uid,
            label: item.name
        }))
    }
}

const tagFilterOptions = ref([])
const columns = computed(() => {
    const baseColumns = [
        {
            label: '序号',
            type: 'index',
            width: 60,
            align: 'center',
            indexMethod: (index) => index + 1
        },
        { label: '商品名称', prop: 'title', slot: 'title', width: 300 },
        { label: '品牌/类别', prop: 'gd_brand' },
        { label: '库存', prop: 'qty' },
        { label: '单价（元）', prop: 'price' },
        { label: '上架', prop: 'onsale', slot: 'onsale' },
        { label: '创建时间', prop: 'atime', width: 150 }
    ]
    return props.isCite ? customColumns.value : baseColumns
})

const customColumns = computed(() => {
    if (!props.isShowTag) {
        return [...(props.extraColumns || [])]
    }
    const extraCols = [...(props.extraColumns || [])]
    const tagColumn = {
        label: '标签',
        prop: 'tag',
        slot: 'tag',
        filters: tagFilterOptions.value,
        filterMethod: filterByTag,
        filterMultiple: true,
        filterable: true,
    }
    // 如果extraCols为空，直接返回标签列
    if (extraCols.length === 0) {
        return [tagColumn]
    }
    // 将标签列插入到倒数第二列
    const insertIndex = Math.max(0, extraCols.length - 1)
    extraCols.splice(insertIndex, 0, tagColumn)
    return extraCols
})

const loadScroll = () => {
    if (isLoading.value || !hasMore.value) return
    custPage.value++
    getGoodsList()
}

// 定义 Emits
const emit = defineEmits([
    'operaStartupHandleEmit',
])

// 选择项目变化，触发事件
const onSelectionChange = (val) => {
    // 多选数据
    console.log('选中的数据==', val)
}

// 点击当前高亮项目，触发事件
const onCurrentChange = (val) => {
    console.log('点击当前高亮项目，触发事件=', val)
}

// 排序函数
const onSortChange = (val) => {
    return
}

const filterByTag = (value, row, column) => {
    // 这里不做实际筛选，因为我们要通过后台接口获取筛选数据
    // 返回 true 让所有数据都显示，实际筛选由后台处理
    return true
}

// 动态修改筛选器按钮样式
const applyFilterButtonStyles = () => {
    // 等待DOM更新
    nextTick(() => {
        const observer = new MutationObserver(() => {
            const filterBottoms = document.querySelectorAll('.el-table-filter__bottom')
            filterBottoms.forEach(bottom => {
                const buttons = bottom.querySelectorAll('button')
                if (buttons.length >= 2) {
                    // 第一个按钮（筛选）
                    const filterBtn = buttons[0]
                    filterBtn.style.cssText = `
                        margin-right: 8px !important;
                        border: 1px solid #dcdfe6 !important;
                        border-radius: 4px !important;
                    `
                    // 第二个按钮（重置）
                    const resetBtn = buttons[1]
                    resetBtn.style.cssText = `
                        background: #f5f5f5 !important;
                        color: #606266 !important;
                        border: 1px solid #dcdfe6 !important;
                        border-radius: 4px !important;
                    `
                }
            })
        })
        observer.observe(document.body, {
            childList: true,
            subtree: true
        })
        // 5秒后停止观察
        setTimeout(() => observer.disconnect(), 5000)
    })
}

// 新增的筛选器变化事件
const onFilterChange = (filters) => {
    console.log('筛选器状态:', filters)
    // Element UI 返回的筛选器数据格式是 { "el-table_3_column_23": ["54", "46"] }
    // 我们需要找到标签列对应的筛选数据
    let tagFilterValues = []
    const tagColumnIndex = columns.value.findIndex(col => col.prop === 'tag')
    console.log('标签列索引:', tagColumnIndex)
    if (tagColumnIndex !== -1) {
        // 查找包含列索引的键名
        const filterKey = Object.keys(filters).find(key => {
            // Element UI 的键名格式通常是 el-table_X_column_Y
            // 其中 Y 是列的索引（从某个数字开始计算）
            const match = key.match(/column_(\d+)/)
            if (match) {
                const columnNum = parseInt(match[1])
                // 可能需要调整这个计算，因为Element UI的列索引可能包含选择列等
                return columnNum === tagColumnIndex ||
                    columnNum === tagColumnIndex + 1 ||
                    columnNum === tagColumnIndex + 2  // 考虑序号列的影响
            }
            return false
        })
        console.log('找到的筛选器键名:', filterKey)
        if (filterKey && filters[filterKey]) {
            tagFilterValues = filters[filterKey]
        }
    }
    // 方法2: 如果方法1失败，使用备用方案（获取第一个筛选器）
    if (tagFilterValues.length === 0) {
        const filterKeys = Object.keys(filters)
        if (filterKeys.length > 0) {
            const firstKey = filterKeys[0]
            const filterValue = filters[firstKey]
            if (Array.isArray(filterValue)) {
                tagFilterValues = filterValue
            }
        }
    }
    // 处理标签筛选
    if (tagFilterValues.length > 0) {
        // 将筛选的标签值传递给查询参数
        goodQuery.value.tagid = tagFilterValues.join(',')
    } else {
        goodQuery.value.tagid = ''
    }
    custPage.value = 0
    tableData.value = []
    getGoodsList()
}

</script>

<style lang="scss" scoped>
.container-page {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    padding: 10px;
    // background: linear-gradient(90deg, #f6f4f7 0%, #faf3fb 100%);
}

.container-card {
    //     box-sizing: border-box;
    //     padding: 8px;
    //     border-radius: 10px;
    height: 100%;
    width: 100%;
    //     border: 1px solid #fff;
    position: relative;
    overflow: hidden;
}

::v-deep .el-tabs__nav {
    .el-tabs__active-bar {
        height: 3px !important;
    }

    .is-active {
        color: #3388ff !important;
        font-weight: bold !important;
    }
}

.row-title {
    position: relative;

    .zhiding-box {
        position: absolute;
        top: 0px;
        right: 0px;

        .zhi-icon {
            width: 12px;
            color: #c00;
        }
    }
}

.El-table {
    position: absolute;
    height: 100%;
    width: 99%;
}

.avatar {
    height: 58px;
    width: 58px;
    border-radius: 3px;
}

.tag-container {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    align-items: center;
}

.tag-item {
    margin: 0;
    max-width: 140px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>
